package com.cellulam.framework.core.model;

import com.cellulam.framework.core.enums.PeriodUnit;
import lombok.Data;

import java.time.LocalDateTime;

@Data
public class PeriodUnitTime {
    /**
     * 值
     */
    private int value;

    /**
     * 单位
     */
    private int unitCode;

    /**
     * 单位
     */
    public PeriodUnit getUnit() {
        return PeriodUnit.valueOf(this.unitCode);
    }

    public PeriodUnitTime() {
        this(0, PeriodUnit.DAY);
    }

    public PeriodUnitTime(int value, PeriodUnit unit) {
        this.value = value;
        this.unitCode = unit.getCode();
    }

    /**
     * 描述
     *
     * @return
     */
    public String getDesc() {
        return this.value + (this.getUnit() == null ? "" : this.getUnit().getDescription());
    }

    public LocalDateTime plus(LocalDateTime date) {
        if (date == null) {
            return null;
        }

        PeriodUnit unit = this.getUnit();

        switch (unit) {
            case YEAR:
                return date.plusYears(this.value);
            case SEASON:
                return date.plusMonths(this.value * 4);
            case MONTH:
                return date.plusMonths(this.value);
            case WEEK:
                return date.plusWeeks(this.value);
            case DAY:
                return date.plusDays(this.value);
            case HOUR:
                return date.plusHours(this.value);
            case MINUTE:
                return date.plusMinutes(this.value);
            case SECOND:
                return date.plusSeconds(this.value);
            default:
                throw new UnsupportedOperationException(unit.name());
        }
    }

    /**
     * 实际含义是被减
     */
    public LocalDateTime minus(LocalDateTime date) {
        if (date == null) {
            return null;
        }
        PeriodUnit unit = this.getUnit();
        switch (unit) {
            case YEAR:
                return date.minusYears(this.value);
            case SEASON:
                return date.minusMonths(this.value * 4);
            case MONTH:
                return date.minusMonths(this.value);
            case WEEK:
                return date.minusWeeks(this.value);
            case DAY:
                return date.minusDays(this.value);
            case HOUR:
                return date.minusHours(this.value);
            case MINUTE:
                return date.minusMinutes(this.value);
            case SECOND:
                return date.minusSeconds(this.value);
            default:
                throw new UnsupportedOperationException(unit.name());
        }
    }
}
